package com.wchat.utils;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : willian fu
 * @version : 1.0
 */
@Component
public class TokenUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public String getUserIdByRequest(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return getUserIdByRedis(getToken(request));
    }

    public String getUserIdByRequest(HttpServletRequest request){
        return getUserIdByRedis(getToken(request));
    }

    public String getTokenByRequest(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return getToken(request);
    }

    public String getUserIdByRedis(String token){
        return redisTemplate.opsForValue().get("token:" + token);
    }

    private String getToken(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        return StrUtil.isBlank(token) ? request.getParameter("token") : token;
    }

    public void delOldToken(){
        redisTemplate.delete("token:" + getTokenByRequest());
    }

    public void delOldToken(String token){
        redisTemplate.delete("token:" + token);
    }
}
